package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.dto.VipDTO;
import com.sky.dto.VipPageQueryDTO;
import com.sky.entity.User;
import com.sky.entity.Vip;
import com.sky.exception.BusinessException;
import com.sky.mapper.UserMapper;
import com.sky.mapper.VipMapper;
import com.sky.result.PageResult;
import com.sky.service.VipService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class VipServiceImpl implements VipService {

    @Autowired
    private VipMapper vipMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 新增会员
     * @param vipDTO
     */
    @Transactional
    public void save(VipDTO vipDTO) {
        log.info("开始新增会员，参数：{}", vipDTO);

        // 验证用户是否存在
        if (vipDTO.getUserId() == null) {
            log.warn("新增会员失败：用户ID不能为空");
            throw new BusinessException("用户ID不能为空");
        }

        User user = userMapper.getById(vipDTO.getUserId());
        if (user == null) {
            log.warn("新增会员失败：用户ID={}不存在", vipDTO.getUserId());
            throw new BusinessException("用户不存在");
        }

        // 检查用户是否已经是会员
        Vip existingVip = vipMapper.getByUserId(vipDTO.getUserId());
        if (existingVip != null) {
            log.warn("新增会员失败：用户ID={}已经是{}会员", vipDTO.getUserId(), existingVip.getLevel());
            throw new BusinessException("该用户已经是会员");
        }

        Vip vip = new Vip();
        BeanUtils.copyProperties(vipDTO, vip);
        vip.setCreateTime(LocalDateTime.now());

        // 如果没有设置开始时间，默认为当前时间
        if (vip.getStartTime() == null) {
            vip.setStartTime(LocalDateTime.now());
        }

        // 如果没有设置结束时间，默认为一月后
        if (vip.getEndTime() == null) {
            vip.setEndTime(vip.getStartTime().plusMonths(1));
        }

        vipMapper.insert(vip);
        log.info("会员新增成功：用户ID={}, 等级={}", vipDTO.getUserId(), vip.getLevel());
    }

    /**
     * 删除会员
     * @param id
     */
    @Transactional
    public void delete(Long id) {
        log.info("开始删除会员，id：{}", id);

        // 验证会员是否存在
        Vip vip = vipMapper.getById(id);
        if (vip == null) {
            log.warn("删除会员失败：会员ID={}不存在", id);
            throw new BusinessException("会员不存在");
        }

        Long userId = vip.getUserId();
        if (userId == null) {
            log.warn("删除会员失败：用户ID={}为空", userId);
            throw new BusinessException("会员关联的用户ID为空");
        }

        User user = userMapper.getById(userId);
        if (user == null) {
            log.warn("删除会员失败：用户ID={}不存在", userId);
            throw new BusinessException("会员关联的用户不存在");
        }

        vipMapper.delete(id);
        log.info("会员删除成功");
    }

    /**
     * 编辑会员信息
     * @param vipDTO
     */
    @Transactional
    public void update(VipDTO vipDTO) {
        log.info("开始更新会员信息，参数：{}", vipDTO);

        // 验证会员和用户是否存在
        if (vipDTO.getId() == null && vipDTO.getUserId() == null) {
            log.warn("更新会员失败：会员id和用户id都为空");
            throw new BusinessException("会员id和用户id不能同时为空");
        }
        if (vipDTO.getUserId() != null) {
            User user = userMapper.getById(vipDTO.getUserId());
            if (user == null) {
                log.warn("更新会员失败：用户ID={}不存在", vipDTO.getUserId());
                throw new BusinessException("用户不存在");
            }
        }

        // 会员id缺省时，验证本条数据是否在会员表中
        Long vipId = vipDTO.getId();
        if (vipId == null) {
            Vip currentVip = vipMapper.getByUserId(vipDTO.getUserId());
            if (currentVip == null) {
                log.warn("更新会员失败：用户ID={}不是会员", vipDTO.getUserId());
                throw new BusinessException("该用户不是会员");
            }
            vipId = currentVip.getId();
        }

        // 会员id和用户id存在时，验证它们在表中是否相符
        if (vipDTO.getId() != null && vipDTO.getUserId() != null){
            Vip currentVip = vipMapper.getByUserId(vipDTO.getUserId());
            if (currentVip == null || currentVip.getId() != vipDTO.getId()) {
                log.warn("更新会员失败：会员ID={}和用户ID={}不在同一条数据中", vipDTO.getId(), vipDTO.getUserId());
                throw new BusinessException("会员ID和用户ID不匹配");
            }
        }

        Vip vip = new Vip();
        BeanUtils.copyProperties(vipDTO, vip);
        vip.setUpdateTime(LocalDateTime.now());
        vip.setId(vipId);

        vipMapper.update(vip);
        log.info("更新会员成功");
    }

    /**
     * 会员分页查询
     * @param vipPageQueryDTO
     * @return
     */
    public PageResult pageQuery(VipPageQueryDTO vipPageQueryDTO) {
        log.info("开始会员分页查询，参数：{}", vipPageQueryDTO);
        PageHelper.startPage(vipPageQueryDTO.getPage(), vipPageQueryDTO.getPageSize());
        Page<Vip> page = vipMapper.pageQuery(vipPageQueryDTO);
        long total = page.getTotal();
        List<Vip> records = page.getResult();
        log.info("会员分页查询完成，总记录数：{}, 当前页记录数：{}", total, records.size());
        return new PageResult(total, records);
    }

    /**
     * 根据id查询会员信息
     * @param id
     * @return
     */
    public Vip getById(Long id) {
        log.info("根据id查询会员信息，id：{}", id);
        Vip vip = vipMapper.getById(id);
        log.info("查询结果：{}", vip);
        return vip;
    }

    /**
     * 根据用户id查询会员信息
     * @param userId
     * @return
     */
    public Vip getByUserId(Long userId) {
        log.info("根据用户id查询会员信息，userId：{}", userId);
        Vip vip = vipMapper.getByUserId(userId);
        log.info("查询结果：{}", vip);
        return vip;
    }
} 